#!/bin/bash
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 06:05:30
# @LastEditTime: 2025-03-14 06:05:35
# @Description: 统一的Docker服务监控脚本
###

# 配置文件路径
CONFIG_FILE="/opt/monitor/config/services.ini"
LOG_FILE="/opt/monitor/logs/service_monitor.log"

# 确保日志目录存在
mkdir -p "$(dirname "$LOG_FILE")"

# 日志函数
log() {
    local level=$1
    local message=$2
    local timestamp=$(date '+%F %T')
    echo "[$timestamp] [$level] $message" | tee -a "$LOG_FILE"
}

# 获取配置值
get_config_value() {
    local section=$1
    local key=$2
    awk -F '=' "/^\[$section\]/{f=1;next} /^\[.*\]/{f=0} f&&/^$key=/{print \$2}" "$CONFIG_FILE"
}

# 检查服务状态
check_service() {
    local service_name=$1
    local container_name=$(get_config_value "$service_name" "container_name")
    local depends_on=$(get_config_value "$service_name" "depends_on")
    local restart_delay=$(get_config_value "$service_name" "restart_delay")
    
    # 默认值
    restart_delay=${restart_delay:-5}
    
    # 检查容器状态
    local status=$(docker inspect -f '{{.State.Status}}' "$container_name" 2>/dev/null)
    
    if [[ "$status" != "running" ]]; then
        log "WARNING" "[$container_name] 状态异常 (当前状态: ${status:-容器不存在})，正在尝试恢复..."
        
        if docker start "$container_name" > /dev/null 2>&1; then
            log "INFO" "[$container_name] 成功重启"
            
            # 如果有依赖服务，也重启它们
            if [[ -n "$depends_on" ]]; then
                log "INFO" "[$container_name] 等待 $restart_delay 秒后重启依赖服务: $depends_on"
                sleep "$restart_delay"
                
                IFS=',' read -ra DEPS <<< "$depends_on"
                for dep in "${DEPS[@]}"; do
                    if docker restart "$dep" > /dev/null 2>&1; then
                        log "INFO" "[$dep] 依赖服务重启成功"
                    else
                        log "ERROR" "[$dep] 依赖服务重启失败"
                    fi
                done
            fi
        else
            log "ERROR" "[$container_name] 重启失败！请手动检查！"
        fi
    else
        log "DEBUG" "[$container_name] 运行正常"
    fi
}

# 主函数
main() {
    # 检查配置文件
    if [[ ! -f "$CONFIG_FILE" ]]; then
        log "ERROR" "配置文件不存在: $CONFIG_FILE"
        exit 1
    fi
    
    # 获取所有服务名称
    services=$(awk -F'[][]' '/^\[.*\]/{print $2}' "$CONFIG_FILE")
    
    # 检查每个服务
    for service in $services; do
        check_service "$service"
    done
}

main "$@"
